package com.cdainfo.vaadin.spring;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

public abstract class Inject {
	
	private Inject() {}

	private static ApplicationContext applicationContext;
	
	private static ApplicationContext getApplicationContext() {
		if(applicationContext==null){
			ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
					.currentRequestAttributes();
			HttpServletRequest request = requestAttributes.getRequest();
			HttpSession session = request.getSession(false);
			applicationContext=WebApplicationContextUtils
					.getRequiredWebApplicationContext(session.getServletContext());
		}
		return applicationContext;
	}
	
	private static <T> T getBean(Class<T> clase,
			ApplicationContext applicationContext) {
		AutowireCapableBeanFactory beanFactory = applicationContext
				.getAutowireCapableBeanFactory();
		return beanFactory.getBean(clase);
	}
	
	public static void inject(Object object){
		AutowireCapableBeanFactory beanFactory=getApplicationContext().getAutowireCapableBeanFactory();
		beanFactory.autowireBeanProperties(object, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
	}
	
	public static void injectScheduler(Object object, ApplicationContext schedulerContext){
		AutowireCapableBeanFactory beanFactory=schedulerContext.getAutowireCapableBeanFactory();
		beanFactory.autowireBeanProperties(object, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
	}
	
	public static <T> T getBean(Class<T> clase){
		return getBean(clase, getApplicationContext());
	}	
	
	public static String getProperty(String parametro)
	{
		PropertiesFactoryBean propertiesFactory = getBean(PropertiesFactoryBean.class);
		try {
			return propertiesFactory.getObject().getProperty(parametro);
		} catch (IOException e) {
			throw new RuntimeException("Error al obtener propiedad '"+parametro+"'",e);
		}
	}
}
